include(ExternalProject)

set(ONNXRUNTIME_DIR ${PROJECT_BINARY_DIR}/onnxruntime)
set(ONNXRUNTIME_INSTALL_DIR ${PROJECT_BINARY_DIR}/install/)
set(ONNXRUNTIME_INCLUDE_DIR "${ONNXRUNTIME_INSTALL_DIR}/include" CACHE PATH "onnxruntime include directory." FORCE)

if (WIN32)
    MESSAGE(STATUS "Now is windows")
    set(ONNXRUNTIME_URL "https://github.com/microsoft/onnxruntime/releases/download/v1.0.0/onnxruntime-win-x64-1.0.0.zip")
    set(ONNXRUNTIME_DOWNLOAD_NAME onnxruntime-win-x64-1.0.0.zip)
    set(ONNXRUMTINE_BUILD_CMD unzip ${ONNXRUNTIME_DIR}/src/onnxruntime-win-x64-1.0.0.zip)
    set(ONNXRUNTIME_LIBRARIES "${ONNXRUNTIME_INSTALL_DIR}/lib/libonnxruntime.dll" CACHE FILEPATH "onnxruntime lib" FORCE)
elseif (APPLE)
    MESSAGE(STATUS "Now is Apple systens.")
    set(ONNXRUNTIME_URL "https://github.com/microsoft/onnxruntime/releases/download/v1.0.0/onnxruntime-osx-x64-1.0.0.tgz")
    set(ONNXRUNTIME_DOWNLOAD_NAME onnxruntime-osx-x64-1.0.0.tgz)
    set(ONNXRUMTINE_BUILD_CMD tar -xzvf ${ONNXRUNTIME_DIR}/src/onnxruntime-osx-x64-1.0.0.tgz)
    set(ONNXRUNTIME_LIBRARIES "${ONNXRUNTIME_INSTALL_DIR}/lib/libonnxruntime.dylib" CACHE FILEPATH "onnxruntime lib" FORCE)
elseif (UNIX)
    set(ONNXRUNTIME_URL "https://github.com/microsoft/onnxruntime/releases/download/v1.0.0/onnxruntime-linux-x64-1.0.0.tgz")
    MESSAGE(STATUS "Now is UNIX-like OS's.")
    set(ONNXRUNTIME_DOWNLOAD_NAME onnxruntime-linux-x64-1.0.0.tgz)
    set(ONNXRUMTINE_BUILD_CMD tar -xzvf ${ONNXRUNTIME_DIR}/src/onnxruntime-linux-x64-1.0.0.tgz)
    set(ONNXRUNTIME_LIBRARIES "${ONNXRUNTIME_INSTALL_DIR}/lib/libonnxruntime.so" CACHE FILEPATH "onnxruntime lib" FORCE)
endif ()

include_directories(${ONNXRUNTIME_INCLUDE_DIR})
set(ONNXRUNTIME_INSTALL_CMD cp -r ${ONNXRUNTIME_DIR}/src/extern_onnxruntime/ ${ONNXRUNTIME_INSTALL_DIR})
ExternalProject_Add(extern_onnxruntime
    URL ${ONNXRUNTIME_URL}
    DOWNLOAD_NAME    ${ONNXRUNTIME_DOWNLOAD_NAME}
    PREFIX ${ONNXRUNTIME_DIR}
    BUILD_COMMAND ${ONNXRUNTIME_BUILD_CMD}
    INSTALL_COMMAND ${ONNXRUNTIME_INSTALL_CMD})

add_library(onnxruntime SHARED IMPORTED GLOBAL)
set_property(TARGET onnxruntime PROPERTY IMPORTED_LOCATION ${ONNXRUNTIME_LIBRARIES})
ADD_DEPENDENCIES(onnxruntime extern_onnxruntime)
LIST(APPEND external_project_dependencies onnxruntime)